package lc20240507;

import java.util.HashMap;

//128.最长连续子序列
public class Demo1 {
    public static void main(String[] args) {
        int[] nums = {100, 4, 200, 1, 3, 2};
        int a = longestConsecutive(nums);
        System.out.println("a = " + a);
    }

    public static int longestConsecutive(int[] nums) {
        int len = nums.length;
        if (len==0){
            return 0;
        }
        HashMap<Integer, Boolean> map = new HashMap<>();
        for (int num : nums) {
            map.put(num, true);
        }

        int longestStreak = 0;
        for (int num : nums) {
            // Check if it's the start of a sequence
            //检查是否包含num[i]-1。
            if (!map.containsKey(num - 1)) {
                int currentNum = num;
                int currentStreak = 1;

                // Increment streak if consecutive numbers exist
                //继续往后遍历，如果满足加一的条件，就curentNum+=1,长度currentStreak += 1;
                while (map.containsKey(currentNum + 1)) {
                    currentNum += 1;
                    currentStreak += 1;
                }

                longestStreak = Math.max(longestStreak, currentStreak);
            }
        }

        return longestStreak;
    }
}
